import { FormationType } from '../types';
import { Team } from '../types/battle';
import { General } from '../models/General';

export class TeamManager {
  private readonly MAX_GENERALS = 3;
  private readonly VALID_FORMATIONS = [
    FormationType.JI_XING,
    FormationType.YAN_XING,
    FormationType.YI_ZI
  ];

  public createTeam(id: string, generals: General[], formation: FormationType): Team | null {
    if (!this.validateTeamSetup(generals, formation)) {
      return null;
    }

    return {
      id,
      generals,
      formation
    };
  }

  private validateTeamSetup(generals: General[], formation: FormationType): boolean {
    // 检查将领数量
    if (generals.length !== this.MAX_GENERALS) {
      console.error('Team must have exactly 3 generals');
      return false;
    }

    // 检查阵型有效性
    if (!this.VALID_FORMATIONS.includes(formation)) {
      console.error('Invalid formation type');
      return false;
    }

    // 检查将领位置是否符合阵型要求
    if (!this.validateFormationPositions(generals, formation)) {
      console.error('General positions do not match formation requirements');
      return false;
    }

    return true;
  }

  private validateFormationPositions(generals: General[], formation: FormationType): boolean {
    const positions = generals.map(g => g.position);

    switch (formation) {
      case FormationType.JI_XING:
        return this.validateJiXingFormation(positions);
      case FormationType.YAN_XING:
        return this.validateYanXingFormation(positions);
      case FormationType.YI_ZI:
        return this.validateYiZiFormation(positions);
      default:
        return false;
    }
  }

  private validateJiXingFormation(positions: number[]): boolean {
    const frontCount = positions.filter(p => p <= 3).length;
    return frontCount === 1;
  }

  private validateYanXingFormation(positions: number[]): boolean {
    const frontCount = positions.filter(p => p <= 3).length;
    return frontCount === 2;
  }

  private validateYiZiFormation(positions: number[]): boolean {
    const frontCount = positions.filter(p => p <= 3).length;
    return frontCount === 3;
  }
}
